/**
 * author      : dormi330
 * date        : 2018/6/29
 * project     : mybatis
 * description : TODO
 */

package com.deep.trade.application.cart;

import com.deep.trade.adaptor.required.member.Member;
import com.deep.trade.adaptor.required.member.MemberService;
import com.deep.trade.adaptor.required.sku.ItemSkuService;
import com.deep.trade.adaptor.required.sku.Sku;
import com.deep.trade.cart.InDtoCart;
import com.deep.trade.cart.InDtoCartDelete;
import com.deep.trade.common.TradeException;
import com.deep.trade.domain.cart.CommandOfCart;
import com.deep.trade.infrastructure.utils.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartService {

    @Autowired
    private MemberService memberService;

    @Autowired
    private ItemSkuService itemSkuService;

    @Autowired
    private CommandOfCart commandOfCart;
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    public void addSkuToCart(InDtoCart inDtoCart) throws Exception {
        logger.info("{}, inDtoCart={}", CommonUtils.currentClassAndMethod(), inDtoCart.toString());

        String tenantCode = inDtoCart.getTenantCode();
        if (null == tenantCode) throw new TradeException("tenantCode cannot be null");

        Member member = memberService.memberOfToken(tenantCode, inDtoCart.getToken());
        if (null == member) throw new TradeException("member.getId() cannot be null");

        String skuId = inDtoCart.getSkuId();
        if (null == skuId) throw new TradeException("skuId cannot be null");
        Sku sku = itemSkuService.skuOfId(tenantCode, skuId);
        if (null == sku) throw new TradeException("sku cannot be found!");

        commandOfCart.addSkuToCart(tenantCode, member.getId(), sku, inDtoCart.getQuantity());
    }

    public void removeSkuFromCart(InDtoCartDelete inDtoCartDelete) throws Exception {
        logger.info("{}, inDtoCart={}", CommonUtils.currentClassAndMethod(), inDtoCartDelete.toString());
        String tenantCode = inDtoCartDelete.getTenantCode();
        Member member = memberService.memberOfToken(tenantCode, inDtoCartDelete.getToken());
        List<String> skuIdList = inDtoCartDelete.getSkuIdList();

        commandOfCart.removeSkuFromCart(tenantCode, member.getId(), skuIdList);
    }

    public void alterQuantity(InDtoCart inDtoCart) throws Exception {
        logger.info("{}, inDtoCart={}", CommonUtils.currentClassAndMethod(), inDtoCart.toString());
        String tenantCode = inDtoCart.getTenantCode();
        Member member = memberService.memberOfToken(tenantCode, inDtoCart.getToken());
        String skuId = inDtoCart.getSkuId();
        int qty = inDtoCart.getQuantity();

        commandOfCart.alterQuantity(tenantCode, member.getId(), skuId, qty);
    }
}
